import { Injectable, Inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map, pluck, switchMap } from 'rxjs/internal/operators';
import { SongSheet, SheetList } from './data-types/common.type';
import { API_CONFIG, ServicesModule } from './services.module';
import { SongService } from './song.service';
import { Observable } from 'rxjs';
import queryString from 'query-string';

export interface SheetParams {
  offset: number;
  limit: number;
  order: 'new' | 'hot';
  cat: string;
}

@Injectable({
  providedIn: ServicesModule
})
export class SheetService {

  constructor(
    private http: HttpClient,
    private songService: SongService,
    @Inject(API_CONFIG) private url: string
  ) { }
  // 获取歌单详情信息
  getSongSheetDetail(id: number) {
    const params = new HttpParams().set('id', id.toString());
    return this.http.get(this.url + '/playlist/detail', {params})
      .pipe(map((res: { playlist: SongSheet}) => res.playlist));
  }
  playSongSheet(id: number) {
    return this.getSongSheetDetail(id)
      .pipe(pluck('tracks'), switchMap(tracks => this.songService.getSongList(tracks)));
  }
  // 获取歌单列表
  getSongSheet(args: SheetParams): Observable<SheetList> {
    const params = new HttpParams({ fromString: queryString.stringify(args) });
    return this.http.get(this.url + '/top/playlist', {params})
      .pipe(map((res: SheetList) => res));
  }
}
